<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores/index'
import { useRouter } from 'vue-router'

// 实例router
const router = useRouter()
// 实列pinia
const userStore = useUserStore()
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: '',
})
// 重置密码
const formRef = ref()
const onReset = () => {
  formRef.value.resetFields()
}
// 修改密码
const onSubmit = async () => {
  // 先进行校验, 校验成功 => 请求, 校验失败 => 自动提示
  // 通过表单标签.value.validate()校验
  await formRef.value.validate()
  console.log('原密码' + userStore.userPassword)
  userStore.userPassword = pwdForm.value.re_pwd
  console.log('新密码' + userStore.userPassword)
  ElMessage.success('修改成功')
  // 清除token
  userStore.setToken('')
  router.push('/login')
}
const checkOldSame = (rule, value, cb) => {
  if (value === pwdForm.value.old_pwd) {
    cb(new Error('原密码和新密码不能一样!'))
  } else {
    cb()
  }
}

const checkNewSame = (rule, value, cb) => {
  if (value !== pwdForm.value.new_pwd) {
    cb(new Error('新密码和确认再次输入的新密码不一样!'))
  } else {
    cb()
  }
}
const rules = {
  // 原密码
  old_pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度必须是6-15位的非空字符串',
      trigger: 'blur',
    },
    {
      // 自定义校验规则
      validator: (rule, value, callback) => {
        // 判断value 和 当前 form 中收集的 password 是否一致
        if (value !== userStore.userPassword) {
          callback(new Error('原密码不正确'))
        } else {
          callback() //就算校验成功了, 也需要callback
        }
      },
      trigger: 'blur',
    },
  ],
  // 新密码
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度必须是6-15位的非空字符串',
      trigger: 'blur',
    },
    { validator: checkOldSame, trigger: 'blur' },
  ],
  // 确认新密码
  re_pwd: [
    { required: true, message: '请再次确认新密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度必须是6-15位的非空字符串',
      trigger: 'blur',
    },
    { validator: checkNewSame, trigger: 'blur' },
  ],
}
</script>
<template>
  <page-container title="重置密码">
    <el-row>
      <el-col :span="12">
        <el-form :model="pwdForm" :rules="rules" ref="formRef" label-width="100px" size="large">
          <el-form-item label="原密码" prop="old_pwd">
            <el-input v-model="pwdForm.old_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="new_pwd">
            <el-input v-model="pwdForm.new_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="re_pwd">
            <el-input v-model="pwdForm.re_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="onSubmit" type="primary">修改密码</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </page-container>
</template>
